"use strict";

import Home         from './views/pages/Home.js'
import About        from './views/pages/About.js'
import Error404     from './views/pages/Error404.js'
import Login     from './views/pages/Login.js'
import Reset from './views/pages/Reset.js'
import Register from "./views/pages/Register.js"

// List of supported routes. Any url other than these routes will throw a 404 error
const routes = {
    '/': Home,
    '/about'      : About,
    '/login'   : Login,
    '/reset': Reset,
    '/register': Register
};
let content;

window.isLogin = async ()=>{
    return !!localStorage.getItem('token')
}

window.checkLogin = async ()=>{
    let token = localStorage.getItem('token'),result=false;
    if(token){
        try{
            result = await $.post(CHECK_URL,{token});
        }catch(err){
            console.log(err.responseText)
        }
    }
    return !!result;
}

window.renderNavBar = async ()=>{
    let result = await window.isLogin()
    if(result){
        $('.logout-item').show()
    }else{
        $('.logout-item').hide()
    }
}

window.sendRequest = (type, url, params, data, headers,success,error,json,form)=>{
    headers = headers||{}
    window.isLogin().then((login)=>{
        if(login){
            headers['token'] = localStorage.getItem('token')
        }
        let wrap_error = (xhr)=>{
            if(xhr.status==401&&xhr.responseText.includes('jwt expired')){
                window.renderNavBar();
                window.onNavigate('/login')
                return
            }
            if(error){
                error(xhr)
            }
        }
        url = url + (params?('?'+$.param(params)):'')
        let options ={
            url: url,
            type: type,
            data: data,
            headers: headers,
            success: success,
            error:wrap_error
        }
        if(json){
            options.data = JSON.stringify(options.data)
            options.contentType = "application/json; charset=utf-8"
            options.processData = false
        }
        if(form){
            options.contentType = false;
            options.processData = false;
        }
        $.ajax(options);
    })
}

window.onNavigate = async (pathName)=>{
    content = document.getElementById('page_container')||document.body;
    window.page_container = content;
    let result = await window.isLogin()
    if(pathName==='/'){
        if(!result){
            let hash = window.location.hash;
            if(!hash||hash.substr(0,2)!=='#P'){
                await window.onNavigate('/login')
                return;
            }
        }
    }else if(pathName==='/logout'){
        localStorage.removeItem('token')
        await window.renderNavBar();
        await window.onNavigate('/login')
        return;
    }
    let page = routes[pathName] ? routes[pathName] : Error404
    content.innerHTML = await page.render();
    await page.after_render();
    window.history.pushState({},pathName,window.location.origin + pathName + window.location.search + window.location.hash)
}

window.onpopstate = async () => {
    let path = window.location.pathname
    let page = routes[path] ? routes[path] : Error404
    content.innerHTML = await page.render();
    await page.after_render();
}

window.crypt = {
    secret : CLIENT_KEY,
    encrypt : function (clear) {
        let cipher = CryptoJS.AES.encrypt(clear, window.crypt.secret);
        cipher = cipher.toString();
        return cipher;
    },
    decrypt : function (cipher) {
        let decipher = CryptoJS.AES.decrypt(cipher, window.crypt.secret);
        decipher = decipher.toString(CryptoJS.enc.Utf8);
        return decipher;
    }
};

window.ScirichonFooter =
    `
    <div id="footer-content" class="row h-100 justify-content-center" style="margin-top:80px">
        <span class="" style="font-size: 14px;">Copyright(c) 
            <a style="color: rgb(150, 150, 150); " href="http://www.beian.miit.gov.cn">&nbsp &nbsp &nbsp 京ICP备19000515号-3</a> 
        </span> 
    </div>
    `

window.adjustCellsIcon = (width,height)=>{
    globalUi.editor.graph.ajdustIcons(width,height)
}

window.createSpinner = function(x, y, size)
{
    size = (size != null) ? size : 24;

    var spinner = new Spinner({
        lines: 12, // The number of lines to draw
        length: size, // The length of each line
        width: Math.round(size / 3), // The line thickness
        radius: Math.round(size / 2), // The radius of the inner circle
        rotate: 0, // The rotation offset
        color: (uiTheme == 'dark') ? '#c0c0c0' : '#000', // #rgb or #rrggbb
        speed: 1.5, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false, // Whether to render a shadow
        hwaccel: false, // Whether to use hardware acceleration
        zIndex: 2e9 // The z-index (defaults to 2000000000)
    });

    // Extends spin method to include an optional label
    var oldSpin = spinner.spin;

    spinner.spin = function(container, label)
    {
        container = container||window.page_container
        var result = false;

        if (!this.active)
        {
            oldSpin.call(this, container);
            this.active = true;

            if (label != null)
            {
                var status = document.createElement('div');
                status.style.position = 'absolute';
                status.style.whiteSpace = 'nowrap';
                status.style.background = '#4B4243';
                status.style.color = 'white';
                status.style.fontFamily = 'Helvetica, Arial';
                status.style.fontSize = '9pt';
                status.style.padding = '6px';
                status.style.paddingLeft = '10px';
                status.style.paddingRight = '10px';
                status.style.zIndex = 2e9;
                status.style.left = Math.max(0, x) + 'px';
                status.style.top = Math.max(0, y + 70) + 'px';

                mxUtils.setPrefixedStyle(status.style, 'borderRadius', '6px');
                mxUtils.setPrefixedStyle(status.style, 'transform', 'translate(-50%,-50%)');

                if (uiTheme != 'dark')
                {
                    mxUtils.setPrefixedStyle(status.style, 'boxShadow', '2px 2px 3px 0px #ddd');
                }

                if (label.substring(label.length - 3, label.length) != '...' &&
                    label.charAt(label.length - 1) != '!')
                {
                    label = label + '...';
                }

                status.innerHTML = label;
                container.appendChild(status);
                spinner.status = status;

                // Centers the label in older IE versions
                if (mxClient.IS_VML && (document.documentMode == null || document.documentMode <= 8))
                {
                    status.style.left = Math.round(Math.max(0, x - status.offsetWidth / 2)) + 'px';
                    status.style.top = Math.round(Math.max(0, y + 70 - status.offsetHeight / 2)) + 'px';
                }
            }

            // Pause returns a function to resume the spinner
            this.pause = mxUtils.bind(this, function()
            {
                var fn = function() { };

                if (this.active)
                {
                    fn = mxUtils.bind(this, function()
                    {
                        this.spin(container, label);
                    });
                }

                this.stop();

                return fn;
            });

            result = true;
        }

        return result;
    };

    // Extends stop method to remove the optional label
    var oldStop = spinner.stop;

    spinner.stop = function()
    {
        oldStop.call(this);
        this.active = false;

        if (spinner.status != null)
        {
            spinner.status.parentNode.removeChild(spinner.status);
            spinner.status = null;
        }
    };

    spinner.pause = function()
    {
        return function() {};
    };

    return spinner;
};

var y = Math.max(document.body.clientHeight || 0, document.documentElement.clientHeight || 0) / 2;
var x = document.body.clientWidth / 2 - 2;
window.spinner = window.createSpinner(x,y,24)

window.addEventListener('load', onNavigate('/'));

window.getGraphxml = ()=>{
    return mxUtils.getXml(globalUi.editor.getGraphXml())
}

